package com.gnuc.thoth.app;

import org.joda.time.DateTime;
import org.joda.time.Minutes;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;

import com.gnuc.thoth.R;
import com.gnuc.thoth.app.screens.CallMain;
import com.gnuc.thoth.app.screens.DataMain;
import com.gnuc.thoth.app.screens.MessagingMain;
import com.gnuc.thoth.app.screens.SyncMain;
import com.gnuc.thoth.framework.Thoth;
import com.gnuc.thoth.framework.ThothLog;
import com.gnuc.thoth.framework.utils.ThothAds;
import com.gnuc.thoth.service.ThothService;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class TabMain extends TabActivity
{
	private static TabMain	instance	= null;
	public Spinner				spinner	= null;
	public TextView			tv			= null;
	
	public static TabMain getInstance()
	{
		if (instance == null)
			instance = new TabMain();
		return instance;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		try
		{
			setContentView(R.layout.thoth_layout);
			Thoth.cx = instance = this;
			Resources res = getResources();
			getTabHost().addTab(getTabHost().newTabSpec("CallMain").setIndicator("", res.getDrawable(R.drawable.t_tab_c)).setContent(new Intent().setClass(this, CallMain.class)));
			getTabHost().addTab(getTabHost().newTabSpec("MessagingMain").setIndicator("", res.getDrawable(R.drawable.t_tab_m)).setContent(new Intent().setClass(this, MessagingMain.class)));
			getTabHost().addTab(getTabHost().newTabSpec("DataMain").setIndicator("", res.getDrawable(R.drawable.t_tab_d)).setContent(new Intent().setClass(this, DataMain.class)));
			getTabHost().addTab(getTabHost().newTabSpec("SyncMain").setIndicator("", res.getDrawable(R.drawable.t_tab_s)).setContent(new Intent().setClass(this, SyncMain.class)));
			for (View tab : getTabHost().getTouchables())
				tab.getLayoutParams().height = 30;
			tv = (TextView) findViewById(R.id.log_filter_label_id);
			spinner = (Spinner) findViewById(R.id.log_filter_spinner);
			ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.log_filter_choice_array, android.R.layout.simple_spinner_item);
			adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
			spinner.setAdapter(adapter);
			getTabHost().setOnTabChangedListener(new TabHost.OnTabChangeListener()
			{
				@Override
				public void onTabChanged(String tabId)
				{
					if (getTabHost().getCurrentTabTag().toLowerCase().equals("syncmain"))
					{
						spinner.setVisibility(View.GONE);
						tv.setVisibility(View.GONE);
					}
					else
					{
						spinner.setVisibility(View.VISIBLE);
						tv.setVisibility(View.VISIBLE);
					}
				}
			});
		}
		catch (Exception e)
		{
			ThothLog.e(e);
			Main.getInstance().mainHandler.sendEmptyMessage(-1);
		}
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		Thoth.Settings.read();
		tv = (TextView) findViewById(R.id.log_filter_label_id);
		spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
		{
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
			{
				tv.setText("Statistics for : " + parent.getItemAtPosition(pos).toString());
				Thoth.Settings.APP_LOG_FILTER = pos;
				Thoth.Settings.write();
				if (getTabHost().getCurrentTabTag().toLowerCase().equals("callmain"))
					CallMain.getInstance().updateStatistics();
				else if (getTabHost().getCurrentTabTag().equalsIgnoreCase("messagingmain"))
					MessagingMain.getInstance().updateStatistics();
				else if (getTabHost().getCurrentTabTag().equalsIgnoreCase("datamain"))
					DataMain.getInstance().updateStatistics();
			}
			
			@Override
			public void onNothingSelected(AdapterView<?> parent)
			{}
		});
		spinner.setSelection(Thoth.Settings.APP_LOG_FILTER, true);
		if ((Minutes.minutesBetween(new DateTime(Thoth.Settings.APP_LAST_SYNC_THOTH), new DateTime())).getMinutes() > 59)
		{
			hdlr.sendEmptyMessage(2);
			Intent i = new Intent(Thoth.cx, ThothService.class);
			i.setAction(String.valueOf(Thoth.REQ.UPDATE_SERVER));
			Thoth.cx.startService(i);
		}
		showAd();
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
		Thoth.Settings.write();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.thoth_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.thoth_about :
				AlertDialog.Builder adb = new AlertDialog.Builder(this);
				View layout = LayoutInflater.from(this).inflate(R.layout.about_layout, null);
				WebView webView = (WebView) layout.findViewById(R.id.webview);
				webView.getSettings().setJavaScriptEnabled(true);
				webView.getSettings().setAllowFileAccess(true);
				webView.getSettings().setPluginsEnabled(true);
				webView.loadUrl("file:///android_asset/about_page.html");
				webView.setWebViewClient(new WebViewLayout());
				adb.setView(layout);
				adb.setTitle("");
				adb.setCancelable(false);
				adb.setPositiveButton("Close", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int id)
					{
						dialog.dismiss();
					}
				});
				adb.create().show();
				return true;
			case R.id.thoth_settings :
				startActivity(new Intent(this, PreferencesMain.class));
				return true;
			case R.id.thoth_sync :
				getTabHost().setCurrentTab(3);
				SyncMain.getInstance().startWebSync();
				return true;
			/*
			case R.id.thoth_savedb :
				ThothLog.backupDb();
				Toast.makeText(this, "Db saved", Toast.LENGTH_SHORT).show();
				return true;
			*/
			default :
				return super.onOptionsItemSelected(item);
		}
	}
	
	class WebViewLayout extends WebViewClient
	{
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url)
		{
			view.loadUrl(url);
			return true;
		}
	}
	
	public void showAd()
	{
		LinearLayout adViewHolder = (LinearLayout) findViewById(R.id.ad_layout);
		AdView adView = new AdView(this, AdSize.BANNER, "a14d899beeed04f");
		adView.setAdListener(new ThothAds());
		((ViewGroup) adViewHolder).addView(adView);
		AdRequest adRequest = new AdRequest();
		// adRequest.setTesting(true);
		adView.loadAd(adRequest);
	}
	
	public Handler	hdlr	= new Handler()
								{
									public void handleMessage(Message msg)
									{
										if (msg.what == 0)
										{
											runOnUiThread(new Runnable()
											{
												@Override
												public void run()
												{
													ImageView gnucAd = (ImageView) findViewById(R.id.ad_gnuc);
													gnucAd.setVisibility(View.VISIBLE);
													gnucAd.setOnClickListener(new View.OnClickListener()
													{
														@Override
														public void onClick(View v)
														{
															Intent i = new Intent(Intent.ACTION_VIEW);
															i.setData(Uri.parse("http://gnuconsultancy.mobify.me"));
															startActivity(i);
														}
													});
												}
											});
										}
										else if (msg.what == 1)
										{
											runOnUiThread(new Runnable()
											{
												@Override
												public void run()
												{
													ImageView gnucAd = (ImageView) findViewById(R.id.ad_gnuc);
													gnucAd.setVisibility(View.GONE);
												}
											});
										}
										else if (msg.what == 2)
										{
											runOnUiThread(new Runnable()
											{
												@Override
												public void run()
												{
													((ProgressBar) findViewById(R.id.app_update_pb)).setVisibility(View.VISIBLE);
													((ImageView)findViewById(R.id.app_icon_id)).setVisibility(View.GONE);
												}
											});
										}
										else if (msg.what == 3)
										{
											runOnUiThread(new Runnable()
											{
												@Override
												public void run()
												{
													((ProgressBar) findViewById(R.id.app_update_pb)).setVisibility(View.GONE);
													((ImageView)findViewById(R.id.app_icon_id)).setVisibility(View.VISIBLE);
												}
											});
										}
									}
								};
}
